<template>
  <view class="exchange-record">
    <customHeader class="exchange-record-title" title="兑换记录"/>
    <scroll-view
      class="scroll-wrap"
      :scrollY="true"
      :refresherEnabled="true"
      :refresher-triggered="refresherTriggered"
      @refresherRefresh="handleRefresherRefresh"
      @scrollToLower="handleScrollToLowerList"
    >
      <view class="exchange-record-wrap">
        <!-- refresher-default-style="none"
    refresher-background="none" -->
        <recordCard v-for="(item, index) in source" :key="index" :info="item" />
        <notRecord v-if="!source.length" />
      </view>
      <at-toast
        :is-opened="is_opened"
        :text="toastText"
        :on-close="handleCloseToast"
      /> </scroll-view
  ></view>
</template>

<script>
import notRecord from "../components/not-record";
import recordCard from "../components/record-card";
import customHeader from "@/components/custom-header";
import { exchangeRecords } from "@/libs/api/exchange-store";
const FIRST_PAGE = 1;
const PER_PAGE = 10;
export default {
  components: {
    notRecord,
    recordCard,
    customHeader
  },
  data() {
    return {
      refresherTriggered: false,
      source: [],
      page: 1,
      pagination: {}
    };
  },
  computed: {
    /**是否禁止触底加载 */
    isNotToLower() {
      const { current_page = 0, total_pages = 0 } = this.pagination;
      return current_page >= total_pages;
    },
    /**是否为首页 */
    isFirstPage() {
      return this.page === FIRST_PAGE;
    }
  },
  created() {
    this.handleGetInfo();
  },
  methods: {
    handleScrollToLowerList() {
      if (this.isNotToLower || this.isLoading) return;
      this.handleGetInfo();
    },
    /**下拉刷新 */
    async handleRefresherRefresh() {
      this.refresherTriggered = true;
      this.page = FIRST_PAGE;
      await this.handleGetInfo();
      this.refresherTriggered = false;
    },
    async handleGetInfo() {
      if (this.isLoading) return;
      this.isLoading = true;
      const { data: { data = [], meta = {} } = {} } = await exchangeRecords({
        page: this.page,
        per_page: PER_PAGE
      }).catch(({ message }) => {
        this.$message(message);
        return { data: {} };
      });
      this.isLoading = false;
      this.isFirstPage
        ? (this.source = data)
        : (this.source = [...this.source, ...data]);
      if (!this.isNotToLower) this.page += 1;
      this.pagination = meta?.pagination || {};
    }
  }
};
</script>

<style lang="scss">
.exchange-record {
  height: 100vh;
  display: flex;
  flex-direction: column;
  &-title {
    background-color: #ffffff;
  }
  &-wrap {
    padding: 44px 30px;
  }
  .scroll-wrap {
    flex: 1;
    overflow-x: hidden;
  }
}
</style>
